import axios from "axios";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
const instance = axios.create({
  baseURL: "http://localhost:9999",
  timeout: 10000,
});
// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const userStore = useUserStore();
    if (userStore.user?.token) {
      config.headers.Authorization = userStore.user.token;
    }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    const userStore = useUserStore();
    const status = error.response?.status;
    if (status === 403) {
      ElMessage.error("登录过期");
      userStore.exitLogin();
      return Promise.reject(error);
    }
    if (status >= 400 && status <= 500)
      ElMessage.error(error.response.data.data);
    return Promise.reject(error);
  }
);
export default instance;
